import cn.edu.dgut.Javabean_object.*;
import cn.edu.dgut.function.readfile;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/login/dgut")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("application/json");response.setCharacterEncoding("UTF-8");
        String token = request.getParameter("token");  //获取token字段
        String appid = "javaee";
        String appsecret = "b3b52e43ccfd";
        String userip = request.getRemoteAddr();     //获取本地ip

        String url = "https://cas.dgut.edu.cn/ssoapi/v2/checkToken";
        // 创建checkToken的参数列表
        List<BasicNameValuePair> paramList = new ArrayList<>();
        paramList.add(new BasicNameValuePair("token",token));
        paramList.add(new BasicNameValuePair("appid",appid));
        paramList.add(new BasicNameValuePair("appsecret",appsecret));
        paramList.add(new BasicNameValuePair("userip",userip));

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse resp = null;
        HttpPost httpPost = new HttpPost(url);
        // 模拟表单
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
        httpPost.setEntity(entity);

        // 执行http请求(带表单)
        resp = httpClient.execute(httpPost);
        //获取openid等响应数据（json格式）
        String  resultString =null;
        if(resp.getEntity()!= null) {
            resultString = EntityUtils.toString(resp.getEntity(), "utf-8");
        }
        Jsonb jsonb = JsonbBuilder.create();
        cn.edu.dgut.Javabean_object.token userer = jsonb.fromJson(resultString, token.class);
        if(Integer.parseInt(userer.getError())!=0){
            //token不是第三方登陆返回的
            response.getWriter().println(resultString);

            response.getWriter().println("非第三方登陆或请求字段过期！");
            return;
        }

        else
        {

            String access_token = userer.getAccess_token();
            String openid = userer.getOpenid();
            String urll=null;
            urll= "https://cas.dgut.edu.cn/oauth/getUserInfo";
            // 增加access_token的参数列表
            List<BasicNameValuePair> paramList2 = new ArrayList<>();
            paramList2.add(new BasicNameValuePair("access_token", access_token));
            paramList2.add(new BasicNameValuePair("openid", openid));

            CloseableHttpClient httpClient2 = HttpClients.createDefault();
            CloseableHttpResponse resp2 = null;
            HttpPost httpPost2 = new HttpPost(urll);
            // 模拟表单
            UrlEncodedFormEntity entity2 = new UrlEncodedFormEntity(paramList2);
            httpPost2.setEntity(entity2);

            // 执行http请求(带表单)
            resp2 = httpClient2.execute(httpPost2);
            //获取openid等响应数据（json格式）
            String  resultString2 =null;
            if(resp2.getEntity()!= null) {
                resultString2 = EntityUtils.toString(resp2.getEntity(), "utf-8");
            }
            Jsonb jsonb2 = JsonbBuilder.create();
            cn.edu.dgut.Javabean_object.access_token userer2 = jsonb2.fromJson(resultString2,access_token.class);
            if(userer2.getError()!=null){
                //access-token错误
                response.getWriter().println(resultString2);
                response.getWriter().println("access-token不存在或已过期");
                return;
            }
            //session记录信息,用户选择莞工中央认证登录，则使用“工号”自动创建一个本地账号，密码预设为“123456”
           userinfo LocalUser = new  readfile().localinfo(userer2.getUsername());
            if(LocalUser==null){        //本地没有该工号的用户
                userinfo localUserInfo = new userinfo(userer2.getUsername(),userer2.getName(),null,null,"123456","xx.png",userer2.getFaculty_title(),userer2.getGroup(),null,null);
                String userJson =jsonb.toJson(localUserInfo);
                new readfile().setUserInfo(userJson);
            }

         String use=null;
            Map<String,String> infoMap = (Map<String, String>) request.getSession().getAttribute("Loginer");
            if(infoMap!=null) {
                EntityManager em = (EntityManager) request.getAttribute("_entity.manager");
                System.out.println("11111111111");
                String user_number = infoMap.get("user_number");
                Person person=em.find(Person.class,user_number);
                System.out.println(person.getEmail());
                System.out.println("11111111112222221");
                Person2 person2 = new Person2( userer2.getUsername(),userer2.getFaculty_title(), userer2.getGroup());
                person.setPerson2( person2);
                System.out.println(person.getPerson2().getFaculty_title());
                em.persist(person2);
                em.persist(person);
            }
            else
            {  EntityManager em = (EntityManager) request.getAttribute("_entity.manager");

                System.out.println("1122222222222222");
                if(em.find(Person2.class,userer2.getUsername())==null) {
                    Person2 person2 = new Person2(userer2.getUsername(), userer2.getFaculty_title(), userer2.getGroup());
                    Person person = new Person(userer2.getUsername(), userer2.getName(), null, null, null, "xx.png", null, null, person2);
                    em.persist(person2);
                    em.persist(person);
                    use=userer2.getUsername();
                }else
                {
                    use=em.find(Person2.class,userer2.getUsername()).getPerson().getUser_number();
                }
            }

            Map<String, String> message = new HashMap<String, String>();
          if(infoMap!=null)       {   String user_number = infoMap.get("user_number");message.put("user_number", user_number);    request.getSession().removeAttribute("Loginer");}
          else                        message.put("user_number", use);
            message.put("name", userer2.getName());
            message.put("faculty_title", userer2.getFaculty_title());
            message.put("group", userer2.getGroup());
            message.put("openid", userer2.getOpenid());
            message.put("wx_openid", userer2.getWx_openid());
            message.put("faculty", userer2.getFaculty());
            HttpSession session = request.getSession(true);
            session.setAttribute("Login", message);

        response.sendRedirect("/userInfo.jsp");  //刷新，重定向到jsp显示信息
    }

    }
}
